import EditText from '@/components/workBench/editText.vue'
import MineInfo from '@/components/workBench/mainInfo.vue'
import ColumnList from '@/components/workBench/columnSelect.vue'
import TagList from '@/components/workBench/tagSelect.vue'

import ReaderFile from '@/components/workBench/readerFile.vue'
import BenchMenu from '@/components/workBench/benchMenu.vue'
import { useWorkBenchStore } from '@/stores/workBenchStore'

import { useCurrActStroe } from '@/stores/currActStore'
import { ref, type Component } from 'vue'
import { useAsyncAxios } from '@/utils/asyncFuncStore'
import { useModalStore } from '@/stores/modalStore'
import { storeToRefs } from 'pinia'
import { useRoute, useRouter } from 'vue-router'
import type {
  ColumnsTags,
  ContentImg,
  ContentText,
  ErrorData,
  ReturnSaveFile,
  WorkImgData,
  workExitTextExport
} from '@/types/loginType'
export default function () {
  const { changeData } = useModalStore()

  const router = useRouter()
  const route = useRoute()
  const columnId = ref('')
  const tags = ref<string[]>([])
  const tagsChild = ref<Component | null>(null)
  const columns = ref<{ columnId: string; columnName: string }[]>([])

  // 文本组件
  const article = ref<Component | null>(null)
  const articleId = (route.query.id as string) || ''
  const btnDisabled = ref(false)
  function getColumnId(value: string) {
    columnId.value = value
  }

  // 请求获取标签、专栏信息
  async function getColumnsTagsList() {
    const { getColumnsTagsSelected } = useAsyncAxios()
    const { status, data } = await getColumnsTagsSelected(articleId)
    if (status === 200) {
      const result = data as ColumnsTags
      columns.value = result.columns
      if (articleId) {
        tags.value = result.tags
      }
    }
  }
  // 保存
  async function saveArticle() {
    const formdata = (await formDataSend('0')) as FormData
    if (formdata) {
      const { postSaveArticle } = useAsyncAxios()
      const { status, data } = await postSaveArticle(formdata)
      if (status === 200) {
        changeData({ status, data: { msg: '保存完成' } })
        // 禁用
        btnDisabled.value = true
        setTimeout(() => {
          router.push({ name: 'work', params: { id: (data as ReturnSaveFile).articleId } })
          btnDisabled.value = false
        }, 800)
      } else {
        changeData({ status, data: data as ErrorData })
      }
    }
  }
  // 发布
  async function publicAtrical() {
    const formdata = (await formDataSend('1')) as FormData
    if (formdata) {
      const { postSaveArticle } = useAsyncAxios()
      const { status, data } = await postSaveArticle(formdata)
      if (status === 200) {
        changeData({ status, data: { msg: '发布完成' } })
        // 禁用
        btnDisabled.value = true
        setTimeout(() => {
          router.push({ name: 'work', params: { id: (data as ReturnSaveFile).articleId } })
          btnDisabled.value = false
        }, 800)
      } else {
        changeData({ status, data: data as ErrorData })
      }
    }
  }

  // 获取要发送到服务器的 formdata
  async function formDataSend(views: string) {
    // 取数据
    const formdata = (article.value as workExitTextExport).getFormData()
    const { currUser } = storeToRefs(useCurrActStroe())
    const { articleData } = storeToRefs(useWorkBenchStore())

    formdata.set('public', views)
    formdata.set('userId', currUser.value.id)
    formdata.set('articleId', articleId)
    formdata.set('columnId', columnId.value)
    if (tagsChild.value) {
      const tags = (tagsChild.value as { dynamicTags: string[] }).dynamicTags
        .map((tag) => {
          return tag.trim()
        })
        .filter((item) => item !== '')
        .join('&')
      formdata.set('tags', tags)
    }

    // 处理图像
    const imgData = articleData.value.filter(
      (item) => item.name.startsWith('contentImg') && (item as WorkImgData).url.startsWith('blob:')
    ) as WorkImgData[]
    // 处理文字 和 http 链接
    articleData.value.forEach((item) => {
      if (item.name.startsWith('contentImg')) {
        const url = (item as ContentImg).url
        if (!url.startsWith('blob:')) {
          formdata.append(item.name, url)
        }
      }
      if (item.name.startsWith('contentText')) {
        const text = (item as ContentText).content
        formdata.append(item.name, text)
      }
    })
    // 获取图像，并发送至服务器
    await Promise.all(
      imgData.map((data) => fetch(data.url).then((respose) => respose.blob()))
    ).then((blobs) => {
      imgData.forEach((item, index) => {
        formdata.append(item.name, blobs[index])
      })
    })
    return formdata
  }

  return {
    MineInfo,
    ColumnList,
    TagList,
    BenchMenu,
    ReaderFile,
    EditText,
    articleId,
    article,
    tags,
    tagsChild,
    columns,
    btnDisabled,
    getColumnId,
    getColumnsTagsList,
    saveArticle,
    publicAtrical
  }
}
